package com.pactera.madp.cp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.common.core.constant.CommonConstants;
import com.pactera.madp.common.core.exception.CheckedException;
import com.pactera.madp.cp.api.dto.beta.WorkNewsGroupDTO;
import com.pactera.madp.cp.api.dto.beta.WorkNewsGroupItemDTO;
import com.pactera.madp.cp.api.entity.beta.WorkNewsGroupEntity;
import com.pactera.madp.cp.api.entity.beta.WorkOriginalEntity;
import com.pactera.madp.cp.api.vo.beta.WorkNewsGroupItemVO;
import com.pactera.madp.cp.api.vo.beta.WorkNewsGroupVO;
import com.pactera.madp.cp.mapper.beta.WorkNewsGroupMapper;
import com.pactera.madp.cp.mapper.beta.WorkOriginalMapper;
import com.pactera.madp.cp.service.WorkNewsGroupService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @title 资讯分组业务表-业务接口实现
 * @date 2022-06-11
 * @author Deming.Chang
 */
@Service
@RequiredArgsConstructor
public class WorkNewsGroupServiceImpl extends ServiceImpl<WorkNewsGroupMapper, WorkNewsGroupEntity> implements WorkNewsGroupService {

    private final WorkOriginalMapper originalMapper;

    @Override
    public List<WorkNewsGroupVO> getFirstGroupList() {
        List<WorkNewsGroupEntity> groupEntityList = baseMapper.selectList(
                Wrappers.<WorkNewsGroupEntity>lambdaQuery()
                        .eq(WorkNewsGroupEntity::getDelFlag, 0)
                        .eq(WorkNewsGroupEntity::getParentId, CommonConstants.MENU_TREE_ROOT_ID)
                        .eq(WorkNewsGroupEntity::getAbandoned, Boolean.FALSE)
                        .orderByAsc(WorkNewsGroupEntity::getGroupId)
        );
        List<WorkNewsGroupVO> groupVOList = new ArrayList<>();
        if(CollUtil.isNotEmpty(groupEntityList)){
            groupEntityList.forEach(entity -> {
                WorkNewsGroupVO vo = new WorkNewsGroupVO();
                BeanUtil.copyProperties(entity, vo);

                List<WorkNewsGroupEntity> entityList2 = baseMapper.selectList(
                        Wrappers.<WorkNewsGroupEntity>lambdaQuery()
                                .eq(WorkNewsGroupEntity::getParentId,entity.getGroupId())
                );
                List<WorkNewsGroupItemVO> groupItemVOList = new ArrayList<>();
                if(CollUtil.isNotEmpty(entityList2)){
                    entityList2.forEach(entity2 -> {
                        WorkNewsGroupItemVO itemVO = new WorkNewsGroupItemVO();
                        BeanUtil.copyProperties(entity2, itemVO);
                        groupItemVOList.add(itemVO);
                    });
                    vo.setChildren(groupItemVOList);
                }else if(CollUtil.isEmpty(entityList2)){
                    vo.setChildren(groupItemVOList);
                }
                groupVOList.add(vo);
            });
        }
        return groupVOList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveGroups(WorkNewsGroupDTO dto) {
        //校验主分组名是否存在
        List<WorkNewsGroupEntity> entities = this.baseMapper.selectList(Wrappers.<WorkNewsGroupEntity>lambdaQuery()
                .eq(WorkNewsGroupEntity::getGroupName, dto.getGroupName())
                .eq(WorkNewsGroupEntity::getParentId, CommonConstants.MENU_TREE_ROOT_ID)
        );
        if(!entities.isEmpty()) {
            throw new CheckedException("主分组名"+dto.getGroupName()+"称已存在");
        }
        // 1.0 添加主分组
        WorkNewsGroupEntity parentEntity = new WorkNewsGroupEntity();
        parentEntity.setParentId(CommonConstants.MENU_TREE_ROOT_ID)
                .setGroupName(dto.getGroupName())
                .setSystem(Boolean.FALSE)
                .setAbandoned(Boolean.FALSE);
        this.save(parentEntity);
        // 2.0 设置分组编码
        parentEntity.setGroupType(parentEntity.getGroupId());
        this.updateById(parentEntity);
        // 3.0 添加子分组
        dto.getChildren().forEach(vo -> {
            WorkNewsGroupEntity entity = new WorkNewsGroupEntity();
            entity.setParentId(parentEntity.getGroupId())
                    .setGroupName(vo.getGroupName())
                    .setSort(vo.getSort())
                    .setSystem(Boolean.FALSE)
                    .setAbandoned(Boolean.FALSE);
            this.save(entity);
            entity.setGroupType(entity.getGroupId());
            this.updateById(entity);
        });
        return Boolean.TRUE;
    }

    @Override
    public Boolean updateGroups(WorkNewsGroupDTO dto) {

        // 1.0 更新主分组
        WorkNewsGroupEntity parentEntity = new WorkNewsGroupEntity();
        parentEntity.setGroupName(dto.getGroupName())
                .setAbandoned(Boolean.FALSE)
                .setGroupId(dto.getGroupId());
        int row = baseMapper.updateById(parentEntity);
        if(row<=0){
            throw new CheckedException("更新失败");
        }else{
            //查询哪些子分组发生变化，被移除的分组底下有资讯删除资讯
            List<WorkNewsGroupEntity> entityS = baseMapper.selectList(
                    Wrappers.<WorkNewsGroupEntity>lambdaQuery()
                            .eq(WorkNewsGroupEntity::getParentId,dto.getGroupId())
            );
            List<WorkNewsGroupItemDTO> itemDTOList = dto.getChildren();

            if(entityS.size()>0) {
                for (int j = 0; j < entityS.size(); j++) {
                    int peg = 0;
                    for (int i = 0; i < itemDTOList.size(); i++) {
                        if (entityS.get(j).getGroupId().equals(itemDTOList.get(i).getGroupId())) {
                            peg = 1;
                            BeanUtil.copyProperties(itemDTOList.get(i), entityS.get(j));
                            //更新只修改名字的子分组
                            baseMapper.updateById(entityS.get(j));
                        }
                    }
                    if (peg == 0) {
                        //删除子分组下资讯
                        originalMapper.delete(Wrappers.<WorkOriginalEntity>lambdaQuery().eq(WorkOriginalEntity::getType, entityS.get(j).getGroupId()));
                        //删除子分组
                        baseMapper.deleteById(entityS.get(j).getGroupId());
                    }
                }
            }
                if(itemDTOList.size()>0){
                //新增新添加的子分组
                for(int  a=0;a<itemDTOList.size();a++) {
                    int peg = 0;
                    for (int b = 0; b < entityS.size(); b++) {
                        if (entityS.get(b).getGroupId().equals(itemDTOList.get(a).getGroupId())){
                            peg = 1;
                        }
                    }
                    if (peg == 0) {
                        //新增子分组
                        WorkNewsGroupEntity entity = new WorkNewsGroupEntity();
                        entity.setParentId(dto.getGroupId())
                                .setGroupName(itemDTOList.get(a).getGroupName())
                                .setSort(itemDTOList.get(a).getSort())
                                .setSystem(Boolean.FALSE)
                                .setAbandoned(Boolean.FALSE);
                        this.save(entity);
                        entity.setGroupType(entity.getGroupId());
                        this.updateById(entity);
                    }
                }
            }
//            //2.0更新子分组
//            HashMap<String,Object> map = new HashMap<String,Object>();
//            map.put("parent_id",dto.getGroupId());
//            List<WorkNewsGroupEntity> entityList = baseMapper.selectByMap(map);
//            baseMapper.deleteByMap(map);
//            if(dto.getChildren().size()>0){
//                dto.getChildren().forEach(itemVo -> {
//                    WorkNewsGroupEntity entity = new WorkNewsGroupEntity();
//                    entity.setParentId(parentEntity.getGroupId())
//                            .setGroupName(itemVo.getGroupName())
//                            .setSort(itemVo.getSort())
//                            .setSystem(Boolean.FALSE)
//                            .setAbandoned(Boolean.FALSE);
//                    this.save(entity);
//                    entity.setGroupType(entity.getGroupId());
//                    this.updateById(entity);
//                });
//            }
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean delGroups(Integer groupId) {
        //判断该分组下是否有子分组
        List<WorkNewsGroupEntity> workNewsGroupEntities = baseMapper.selectList(
                Wrappers.<WorkNewsGroupEntity>lambdaQuery()
                        .eq(WorkNewsGroupEntity::getParentId, groupId)
        );
        if(workNewsGroupEntities.size()>0){
            throw new CheckedException("该分组下有子分组，禁止删除！");
        }else {
            //删除分组下资讯
            originalMapper.delete(Wrappers.<WorkOriginalEntity>lambdaQuery().eq(WorkOriginalEntity::getType,groupId));
            //删除分组
            baseMapper.deleteById(groupId);
        }

        return Boolean.TRUE;
    }

    @Override
    public WorkNewsGroupVO getByGroupId(Integer groupId) {
        WorkNewsGroupEntity entity = baseMapper.selectById(groupId);
        WorkNewsGroupVO vo = new WorkNewsGroupVO();
        BeanUtil.copyProperties(entity, vo);
        if(ObjectUtil.isNotNull(entity)){
            List<WorkNewsGroupEntity> childrenEntities = baseMapper.selectList(
                    Wrappers.<WorkNewsGroupEntity>lambdaQuery()
                            .eq(WorkNewsGroupEntity::getDelFlag, CommonConstants.STATUS_NORMAL)
                            .eq(WorkNewsGroupEntity::getParentId, groupId)
                            .eq(WorkNewsGroupEntity::getAbandoned, Boolean.FALSE)
                            .orderByAsc(WorkNewsGroupEntity::getGroupId)
            );
            List<WorkNewsGroupItemVO> children = new ArrayList<>(childrenEntities.size());
            childrenEntities.forEach(itemEntity -> {
                WorkNewsGroupItemVO itemVO = new WorkNewsGroupItemVO();
                BeanUtil.copyProperties(itemEntity, itemVO);
                children.add(itemVO);
            });
            vo.setChildren(children);
        }
        return vo;
    }

    @Override
    public String getNameByType(Integer type, Integer parentId) {
        WorkNewsGroupEntity entity = baseMapper.selectOne(
                Wrappers.<WorkNewsGroupEntity>lambdaQuery()
                        .eq(WorkNewsGroupEntity::getDelFlag, CommonConstants.STATUS_NORMAL)
                        .eq(WorkNewsGroupEntity::getParentId, parentId)
                        .eq(WorkNewsGroupEntity::getGroupType, type)
                        .eq(WorkNewsGroupEntity::getAbandoned, Boolean.FALSE)
        );
        if(ObjectUtil.isNotNull(entity)){
            return entity.getGroupName();
        }
        return StrUtil.EMPTY;
    }
}
